require('es6-promise').polyfill();

import axios from 'axios'

function loadDeliverys(data) {
  return {
    type: 'LOAD_DELIVERY_DATA',
    data
  }
}

function createDelivery(data, response) {
  return {
    type: 'CREATE_DELIVERY_DATA',
    data,
    response
  }
}

function loadDeliveryTemplate(data) {
  return {
    type: 'LOAD_DELIVERY_TEMPLATE',
    data
  }
}

function loadAllTemplate(data) {
  return {
    type: 'LOAD_ALL_TEMPLATE',
    data
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

export function createDeliveryAsync(data) {
  return function(dispatch) {
    return axios.post('/api/delivery/create', data).then(
      resp => dispatch(loadMessagesAsync({})),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}


export function loadMessagesAsync(data) {
  return function(dispatch) {
    return axios.post('/api/pushMessage', data).then(
      resp => dispatch(loadDeliverys(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function loadDeliveryTemplateAsync(data) {
  return function(dispatch) {
    return axios.post('/api/pushMessage/getTemplate', data).then(
      resp => dispatch(loadDeliveryTemplate(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function updateDeliveryTemplateAsync(data) {
  return function(dispatch) {
    return axios.post('/api/pushMessage/updateTemplate', data).then(
      resp => dispatch(loadDeliveryTemplateAsync(data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function loadAllTemplateAsync(data) {
  return function(dispatch) {
    return axios.post('/api/pushMessage/queryTemplatesByProperty', data).then(
      resp => dispatch(loadAllTemplate(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

export function updateAllTemplateAsync(data) {
  return function(dispatch) {
    return axios.post('/api/pushMessage/updateTemplatesByProperty', data).then(
      resp => console.log("success"),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}
